from recommendation_service import RecommendationService
import time
import random
import pandas as pd
import os


def print_recommendations(recommendations):
    """打印推荐结果"""
    # 打印推荐商品标题
    print("\n推荐商品:")
    # 遍历推荐列表
    for i, rec in enumerate(recommendations["recommendations"], 1):
        # 打印推荐商品的详细信息
        print(
            f"{i}. [{rec['category']}] {rec['name']} - {rec['flavor']}味 | ¥{rec['price']} | 得分: {rec['score']:.4f}")



def main():
    # 初始化推荐服务
    print("=== 好想来零食个性化推荐系统 ===")
    service = RecommendationService(data_dir="data")

    # 系统配置
    USER_COUNT = 3000
    PRODUCT_COUNT = 1000
    INTERACTION_COUNT = 100000

    # 初始化系统（自动保存生成的数据）
    service.initialize(
        user_count=USER_COUNT,
        product_count=PRODUCT_COUNT,
        interaction_count=INTERACTION_COUNT,
        save_data=True
    )

    # 获取系统统计
    stats = service.get_system_stats()
    print(f"\n系统统计:")
    print(f"- 用户数量: {stats['total_users']}")
    print(f"- 商品数量: {stats['total_products']}")
    print(f"- 行为日志: {stats['total_interactions']}")
    print(f"- 初始化时间: {stats['last_init_time'].strftime('%Y-%m-%d %H:%M:%S')}")

    # 测试单个用户推荐
    sample_user = f"U{random.randint(1, USER_COUNT):05d}"
    print(f"\n测试单个用户推荐: {sample_user}")

    # 获取推荐结果（包含用户画像，自动保存推荐结果）
    recommendations = service.get_recommendations(
        sample_user,
        top_n=5,
        include_profile=True,
        save_results=True
    )

    # 打印用户画像
    profile = recommendations["user_profile"]
    if profile["status"] == "success":
        print("\n用户画像:")
        print(f"- 年龄组: {profile['base_profile']['age_group']}")
        print(f"- 性别: {profile['base_profile']['gender']}")
        print(f"- 口味偏好: {profile['base_profile']['preference']}")
        print(f"- 价格敏感度: {profile['base_profile']['price_sensitivity']}")

        # 打印行为分析
        behavior = profile['behavior_profile']
        if behavior['total_actions'] > 0:
            print(f"\n行为分析:")
            print(f"- 总交互次数: {behavior['total_actions']}")
            print(f"- 购买转化率: {behavior['buy_ratio']:.2%}")
            print(f"- 偏好品类: {behavior['preferred_category']}")
            print(f"- 偏好口味: {behavior['preferred_flavor']}")
            print(f"- 价格区间: {behavior['preferred_price_range']}")

    # 打印推荐结果
    print_recommendations(recommendations)

    # 批量推荐测试
    print("\n测试批量推荐...")
    batch_users = [f"U{random.randint(1, USER_COUNT):05d}" for _ in range(3)]
    batch_results = service.batch_recommendations(batch_users, top_n=3, save_results=True)

    print("\n批量推荐结果摘要:")
    for res in batch_results:
        if "error" in res:
            print(f"- 用户 {res['user_id']}: 错误 - {res['error']}")
        else:
            rec_names = [r['name'] for r in res['recommendations']]
            print(f"- 用户 {res['user_id']}: {', '.join(rec_names)}")

    # 数据文件列表
    print("\n生成的数据文件:")
    data_dir = service.data_dir
    for file in os.listdir(data_dir):
        if file.startswith(service.run_id):
            filepath = os.path.join(data_dir, file)
            size_mb = os.path.getsize(filepath) / (1024 * 1024)
            print(f"- {file} ({size_mb:.2f} MB)")



if __name__ == "__main__":
    main()


